import Vue from 'vue';
import router from './index';
import { Toast } from 'vant';

Vue.use(Toast);

router.beforeEach((to, from, next) => {
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });
    setTimeout(() => {
        if (window.api != undefined) {
            // 判断是否断网
            api.addEventListener({
                    name: 'offline',
                },
                ret => {
                    if (ret) {
                        next('/offline')
                    }
                }
            );

            // 判断是否有网

            api.addEventListener({
                    name: 'online',
                },
                ret => {
                    if (ret) {
                        router.go(-1);
                    }
                }
            );

            // APP端返回上一页事件

            if (api.systemType === 'ios') {
                if (!to.meta.closeApp) {
                    // IOS端监听返回事件
                    setTimeout(() => {
                        api.addEventListener({
                                name: 'swiperight',
                            },
                            () => {
                                router.go(-1);
                            }
                        );
                    }, 100);
                } else {
                    setTimeout(() => {
                        api.addEventListener({
                                name: 'swiperight',
                            },
                            () => {
                                return;
                            }
                        );
                    }, 100);
                }
            } else {
                // 安卓端监听返回事件
                let isBack = false;
                api.addEventListener({
                        name: 'my_keyback',
                    },
                    (ret, err) => {
                        if (to.meta.closeApp && to.meta.closeApp === true) {
                            if (isBack) {
                                api.closeWidget({
                                    id: api.appId,
                                    retData: {
                                        name: 'closeWidget',
                                    },
                                    silent: true,
                                });
                            } else {
                                isBack = true;
                                api.toast({
                                    msg: '再按一次退出应用',
                                });
                                setTimeout(() => {
                                    isBack = false;
                                }, 2000);
                            }
                        } else {
                            router.go(-1);
                        }
                    }
                );
            }
        }
    }, 310)
    next();
});

router.afterEach(() => {
    Toast.clear();
});